import { Member, IMembers } from './Member'
import {RoomInterface, MediaOptions, MemberBase, MemberInterface} from '../utils/types'


// 房间说话模式
export enum ConferenceModeEnums {
  /**
   * 抢麦模式
   * - 抢到麦才能说话
   * - 释放麦之后，其他人可以抢麦
   */
  SNATCH = 'SNATCH',

  /**
   * 轮流模式
   * - 按下说话键，可以说话
   * - 释放按键后，不能说话
   */
  POLLING = 'POLLING',

  /**
   * 默认模式 - 都可以说话
   */
  DEFAULT = 'DEFAULT',
}

export class Room extends RoomInterface {
  readonly members: IMembers = {};
  // 媒体约束
  protected media: MediaOptions = {};

  // 会话模式: POLLING: 抢麦模式; DEFAULT: 默认模式
  protected conferenceMode: ConferenceModeEnums = ConferenceModeEnums.DEFAULT;
  /**
   * 抢麦模式下的 麦序所属者
   */
  protected speaker: MemberBase | null = null;

  setMember (member: MemberInterface) {
    if (member instanceof Member) {
      this.members[member.userId] = member as Member
    } else {
      this.members[member.userId] = new Member(member)
    }
  }

  getMember (userId) {
    return this.members[userId]
  }

  hasSpeaker () {
    return !!this.speaker
  }

  setSpeaker (speaker) {
    if (!this.hasSpeaker()) {
      this.speaker = speaker
    } else {
      console.error('speaker is ')
    }
  }

  getSpeaker () {
    return this.speaker
  }

  removeSpeaker () {
    this.speaker = null
  }

  removeMember (userId: string) {
    delete this.members[userId]
  }

  getMembers (): Member[] {
    const { members } = this;
    const __members: any[] = [];

    for (const userId in members) {
      if (members.hasOwnProperty(userId)) {
        __members.push(members[userId as string] as Member)
      }
    }
    return __members
  }

  setMediaOption (mediaOptions: MediaOptions) {
    this.media = mediaOptions
  }

  getMediaOption () {
    return this.media
  }
}

export interface Rooms {
  [classId: string]: Room
}

